<template>
  <div>
    <!-- <SearchCusinfo ref="SearchCusinfo" :parentObj="this"></SearchCusinfo> -->
    <a-drawer
      title="选择出库单"
      width="70%"
      placement="right"
      :visible="visible"
      @close="
        () => {
          this.visible = false
        }
      "
      :body-style="{ paddingBottom: '80px' }"
    >
      <div style="margin-bottom: 10px;" class="table-page-search-wrapper">
        <h2>客户:{{ this.cusname }}</h2>
        <a-input
          style="width: 200px;margin-right: 8px;"
          v-model="OutboundOrder"
          placeholder="出库单号"
          @keydown.enter="getDataList" />
        <a-select
          v-model="start"
          style="width: 100px;margin-left: 8px;"
          @change="changeTime"
          name="radioGroup"
          :default-value="0">
          <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
            {{ i }}
          </a-select-option>
        </a-select>
        <a-range-picker style="margin:0 8px;width: 220px;" :disabled="timeDisabled" v-model="time" />
        <a-button
          type="primary"
          @click="() => {
            this.pagination.current = 1
            this.getDataList()
          }">查询</a-button>
      </div>
      <a-table
        ref="table"
        :scroll="{ x: 800 }"
        :columns="columns"
        :rowKey="(row) => row.OutboundOrder+''"
        :dataSource="data"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :rowSelection="rowSelection1"
        :bordered="true"
        size="small">
      </a-table>
      <!-- -- 开票信息 -->

    </a-drawer>
    <div>
      <a-drawer
        :title="info"
        width="90%"
        :visible="visiblees"
        @close="
          () => {
            if(this.details){
              this.visible = false
            }
            this.visiblees = false;
            this.data2 = [];
            this.allData = [];
          }
        "
        :body-style="{ paddingBottom: '120px' }"
      >

        <a-form-model :rules="rules" ref="ruleForm" :model="entity" v-bind="layout">
          <a-row>
            <a-col :span="8">
              <a-form-model-item label="客户名称:" prop="cusname">
                <span autocomplete="off" :disabled="true">{{ this.cusname }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="购货方" prop="DicKey">
                <span>{{ this.name }}</span>
                <!-- <a-select v-if="this.buyPeople.length>0"   placeholder="请选择购货方">
                  <a-select-option v-for="item in buyPeople" :key="item" :value="item.Id" >
                    {{ item. }}
                  </a-select-option>
                </a-select> -->
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="税号" prop="zhanghu">
                <span :disabled="details" @input="(e)=>{ }" placeholder="税号" >{{ entity.zhanghu }}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="8">
              <a-form-model-item label="开户行及账号::" prop="kaihu">
                <span :disabled="details" autocomplete="off" placeholder="开户行" >{{ entity.kaihu }}</span>
              </a-form-model-item>
            </a-col>

            <a-col :span="8">
              <a-form-model-item label="地址、电话:" prop="phone">
                <span :disabled="details" autocomplete="off" placeholder="电话" >{{ entity.phone }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="说明:" prop="Remarks">
                <span :disabled="details" autocomplete="off" placeholder="说明" >{{ entity.Remarks }}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row> </a-row>
          <div style="text-align: right;">
            <a-button v-if="!details" :disabled="this.selectedRowKeys1.length <= 0" type="primary" icon="form" @click="batchChangePrice" >批量改价</a-button>
          </div>
          <div style="padding-bottom: 10%;margin-top: 8px;">
            <div v-if="Summary">
              <a-tabs default-active-key="1" v-model="setTab" @change="callback">
                <a-tab-pane key="1" tab="明细">
                  <a-table
                    ref="table"
                    :scroll="{ y: tableHeight, x: tableWidth }"
                    :columns="columns0"
                    :dataSource="data2"
                    :pagination="false"
                    :rowKey="row => row.detailcode"
                    :loading="loadingApply"
                    :bordered="true"
                    :row-selection="details ? null : rowSelection"
                    size="small"
                  >
                    <template slot="TM_Name" slot-scope="text, record">
                      <CompanySelect
                        v-if="!details"
                        style="width: 100%;"
                        v-model="record.TM_Name"
                        :UnitGroupId="record.ventorycode"
                        :disabled="details"
                        @input="setName($event, record)"
                        @select="project($event, record)"
                      ></CompanySelect>
                      <span v-else >{{ record.TM_Name }}</span>
                    </template>
                    <template slot="Price" slot-scope="text, record">
                      <a-input v-if="!details" :disabled="details" style="width:100%;text-align: right;" v-model="record.Price" @change="(e) => handlePriceChange(e, record)" ></a-input>
                      <span v-else>{{ record.Price | NumberFormatss }}</span>
                    </template>
                    <template slot="numskk" slot-scope="text, record, index">
                      <a-input-number v-if="!details" :disabled="details" style="width:100%" v-model="record.numskk" @change="(e) => handleValChange(e, record, index)" ></a-input-number>
                      <span v-else>{{ record.numskk }}</span>
                    </template>
                    <template slot="markup" slot-scope="text, record">
                      <template v-if="!details">
                        <a-input-number :disabled="details" style="width:80%" v-model="record.markup" @change="(e) => handleValChange(e, record, index, true)" ></a-input-number><span>%</span>
                      </template>
                      <span v-else>{{ record.markup }}</span>
                    </template>
                    <span slot="action" slot-scope="text, record">
                      <template>
                        <a v-if="!details" @click="handleDelete([record])">删除</a>
                      </template>
                    </span>
                  </a-table>
                </a-tab-pane>
                <a-tab-pane key="2" tab="汇总" >
                  <a-table
                    ref="table"
                    :scroll="{ y: tableHeight, x: 800 }"
                    :columns="SummaryColumns"
                    :dataSource="SummaryData"
                    :pagination="false"
                    :rowKey="row => row.detailcode"
                    :loading="loadingApply"
                    :bordered="true"
                    :row-selection="details ? null : rowSelection"
                    size="small"
                  >
                    <template slot="TM_Name" slot-scope="text, record">
                      <CompanySelect
                        v-if="!details"
                        style="width: 100%;"
                        v-model="record.TM_Name"
                        :UnitGroupId="record.ventorycode"
                        :disabled="details"
                        @input="setName($event, record)"
                        @select="project($event, record)"
                      ></CompanySelect>
                      <span v-else >{{ record.TM_Name }}</span>
                    </template>
                    <template slot="InvoicingPrice" slot-scope="text, record">
                      <a-input v-if="!details" :disabled="details" style="width:100%;text-align: right;" v-model="record.InvoicingPrice" @change="(e) => handlePriceChange(e, record)" ></a-input>
                      <span v-else>{{ record.InvoicingPrice | NumberFormatss }}</span>
                    </template>
                    <template slot="InvoicingQuantity" slot-scope="text, record, index">
                      <a-input-number v-if="!details" :disabled="details" style="width:100%" v-model="record.InvoicingQuantity" @change="(e) => handleValChange(e, record, index)" ></a-input-number>
                      <span v-else>{{ record.InvoicingQuantity }}</span>
                    </template>
                    <template slot="markup" slot-scope="text, record">
                      <template v-if="!details">
                        <a-input-number :disabled="details" style="width:80%" v-model="record.markup" @change="(e) => handleValChange(e, record, index, true)" ></a-input-number><span>%</span>
                      </template>
                      <span v-else>{{ record.markup }}</span>
                    </template>
                    <span slot="action" slot-scope="text, record">
                      <template>
                        <a v-if="!details" @click="handleDelete([record])">删除</a>
                      </template>
                    </span>
                  </a-table>
                </a-tab-pane>
              </a-tabs>
            </div>
            <a-table
              v-else
              ref="table"
              :scroll="{ y: tableHeight, x: tableWidth }"
              :columns="columns0"
              :dataSource="data2"
              :pagination="false"
              :rowKey="row=>row.detailcode"
              :loading="loadingApply"
              :bordered="true"
              :row-selection="details?null: rowSelection"
              size="small"
            >
              <template slot="TM_Name" slot-scope="text, record">
                <CompanySelect
                  v-if="!details"
                  style="width: 100%;"
                  v-model="record.TM_Name"
                  :UnitGroupId="record.ventorycode"
                  :disabled="details"
                  @input="setName($event, record)"
                  @select="project($event, record)"
                ></CompanySelect>
                <span v-else >{{ record.TM_Name }}</span>
              </template>
              <template slot="Price" slot-scope="text, record">
                <a-input v-if="!details" :disabled="details" style="width:100%;text-align: right;" v-model="record.Price" @change="(e) => handlePriceChange(e, record)" ></a-input>
                <span v-else>{{ record.Price | NumberFormatss }}</span>
              </template>
              <template slot="numskk" slot-scope="text, record, index">
                <a-input-number v-if="!details" :disabled="details" style="width:100%" v-model="record.numskk" @change="(e) => handleValChange(e, record,index)" ></a-input-number>
                <span v-else>{{ record.numskk }}</span>
              </template>
              <template slot="markup" slot-scope="text, record">
                <template v-if="!details">
                  <a-input-number :disabled="details" style="width:80%" v-model="record.markup" @change="(e) => handleValChange(e, record, index, true)" ></a-input-number><span>%</span>
                </template>
                <span v-else>{{ record.markup }}</span>
              </template>
              <span slot="action" slot-scope="text, record">
                <template>
                  <a v-if="!details" @click="handleDelete([record])">删除</a>
                </template>
              </span>
            </a-table>

          </div>
          <p></p>
          <a-row class="active" style="position: absolute; bottom: 5%;left:0;z-index: 999999; width: 100%;">
            <p style="text-align: right;margin-right: 20px;">价税合计<span></span> {{ Amount | NumberFormats }}</p>
            <a-col :span="8">
              <a-form-model-item label="收票人:" prop="shoupiaoren">
                <!-- <a-select :disabled="details"  v-model="entity.shoupiaoren">
                  <a-select-option v-for="item in options" :key="item.value"  :title="item.label">
                    {{ item.label }}
                  </a-select-option>
                </a-select> -->
                <span :disabled="details" autocomplete="off" placeholder="收票人" >{{ entity.shoupiaoren }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="手机号:" prop="Phone">
                <span :disabled="details" autocomplete="off" placeholder="收票人手机号" >{{ entity.Phone }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="收票地址:" prop="shoupiaodizhi">
                <span :disabled="details" autocomplete="off" placeholder="收票地址" >{{ entity.shoupiaodizhi }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="邮箱地址:" prop="cCusEmail">
                <span :disabled="details" autocomplete="off" placeholder="邮箱地址" >{{ entity.cCusEmail }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="备注" prop="beizhu">
                <span :disabled="details" autocomplete="off" placeholder="备注" >{{ entity.beizhu }}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- </a-row>
          <a-row> -->

        </a-form-model>
        <div
          class="active"
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            textAlign: 'right',
            zIndex: 9999999999,
          }"
        >
          <a-button v-if="!details" :style="{ marginRight: '8px' }" @click="shouorderforgoods">上一步</a-button>
          <a-button v-if="!details" type="primary" @click="SummarySubmission">下一步</a-button>
          <a-button v-if="details" type="primary" @click="closeDetails">取消</a-button>

        </div>
      </a-drawer>
    </div>
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button v-if="!cancel" :style="{ marginRight: '8px' }" @click="shouCusinfo">上一步</a-button>
      <a-button v-if="cancel" :style="{ marginRight: '8px' }" @click="()=>{this.visible = false;}">取消</a-button>
      <a-button type="primary" @click="handleSubmit">下一步</a-button>
    </div>
    <!-- 批量改价 -->
    <a-modal
      title="批量改价"
      :visible="changeVisible"

      @ok="handleChangePrice"
      @cancel="()=>{this.changeVisible=false;this.changeMarkup ='';}"
    >
      <div>
        <span>加成率：</span>
        <a-input-number v-model="changeMarkup"></a-input-number>%
      </div>
    </a-modal>
    <a-drawer
      title="预览"
      :width="'100%'"
      :visible="visiblity"
      @close="handleCancel"
    >
      <div style="width:1200px;margin: 0 auto;">
        <template>
          <div id="tabPage2" >
            <div id="tabPage-zzszyfp">
              <h1 id="fpcc_zp" style="color:#015293;padding:5px 0px 5px 0px; text-align:center;"><strong>增值税专用发票(票样)</strong></h1>
              <table border="0" cellpadding="0" cellspacing="0" style="width:100%">
                <tbody><tr height="30">
                  <td class="align_left">发票代码：<span class="content_td_blue" id="fpdm_zp"></span></td>
                  <td>&nbsp;</td>
                  <td class="align_left">发票号码：<span class="content_td_blue" id="fphm_zp"></span></td>
                  <td>&nbsp;</td>
                  <td class="align_left">开票日期：<span class="content_td_blue" id="kprq_zp"></span></td>
                  <td>&nbsp;</td>
                  <td class="align_left">校验码：<span class="content_td_blue" id="jym_zp"></span></td>
                  <td>&nbsp;</td>
                  <td class="align_left" id="jqxx_zp" style="display:none">机器编号：<span class="content_td_blue" id="jqbh_zp"></span></td>
                  <td>&nbsp;</td>
                </tr>
                </tbody></table>
              <table style="width:100%" border="1" cellspacing="0" cellpadding="0" class="fppy_table">
                <tbody><tr>
                         <td rowspan="4" class="align_center" width="20"><p>购</p>
                           <p>买</p>
                           <p>方</p></td>
                         <td class="align_left borderNo" width="105">名称：</td>
                         <td nowrap="" class="align_left borderNo bgcolorWhite"><span class="content_td_blue" id="gfmc_zp">{{ this.name }}</span></td>

                         <td rowspan="4" class="align_center" width="20">
                           <p></p>
                           <p></p>
                           <p></p></td>
                         <td id="password_zp" rowspan="4" nowrap="" class="align_left " width="350">&nbsp;</td>
                       </tr>
                  <tr>
                    <td class="align_left borderNo">纳税人识别号：</td>
                    <td nowrap="" class="align_left borderNo"><span class="content_td_blue" id="gfsbh_zp">{{ entity.zhanghu }}</span></td>
                  </tr>
                  <tr>
                    <td class="align_left borderNo" valign="top">地址、电话：</td>
                    <td class="align_left borderNo" valign="top"><span class="content_td_blue" id="gfdzdh_zp">{{ entity.phone }} </span></td>
                  </tr>
                  <tr>
                    <td class="align_left borderNo" valign="top">开户行及账号：</td>
                    <td class="align_left borderNo" valign="top"><span class="content_td_blue" id="gfyhzh_zp">{{ entity.kaihu }}</span></td>

                  </tr>

                  <tr>
                    <td colspan="5"><table cellspacing="0" cellpadding="0" style="width:100%;" class="fppy_table_box">
                      <tbody><tr id="tab_head_zp">
                               <td class="align_center borderRight" width="30%">货物或应税劳务、服务名称</td>
                               <td class="align_center borderRight" width="10%">规格型号</td>
                               <td class="align_center borderRight" width="5%">单位</td>
                               <td class="align_center borderRight" width="10%">数量</td>
                               <td class="align_center borderRight" width="10%">单价</td>
                               <td class="align_center borderRight" width="15%">金额</td>
                               <td class="align_center borderRight" width="5%">税率</td>
                               <td class="align_center" width="15%">税额</td>
                             </tr>
                        <tr v-for="(item,index) in data2" :key="index">
                          <td class="align_center borderRight" width="30%">{{ item.TM_Name }}</td>
                          <td class="align_center borderRight" width="10%">{{ item.TM_Specs }}</td>
                          <td class="align_center borderRight" width="5%">{{ item.TM_Unit }}</td>
                          <td class="align_center borderRight" width="10%">{{ item.numskk }}</td>
                          <td class="align_center borderRight" width="10%">{{ item.Price | NumberFormatsss }}</td>
                          <td class="align_center borderRight" width="15%">{{ item.kmoneys }}</td>
                          <td class="align_center borderRight" width="5%">{{ item.TaxRate }}</td>
                          <td class="align_center" width="15%">{{ item.TaxPrice }}</td>
                        </tr>
                        <!-- <tr>
                        <td class="align_center borderRight">合计</td>
                        <td class="align_center borderRight">&nbsp;</td>
                        <td class="align_center borderRight">&nbsp;</td>
                        <td class="align_center borderRight">&nbsp;</td>
                        <td class="align_center borderRight">&nbsp;</td>
                        <td class="align_right borderRight"><span class="content_td_blue" id="je_zp"></span></td>
                        <td class="align_center borderRight">&nbsp;</td>
                        <td class="align_right"><span class="content_td_blue" id="se_zp"></span></td>
                      </tr> -->
                        <tr>
                          <td class="align_center borderRight borderTop"></td>
                          <td colspan="4" class="align_left borderTop"><span class="content_td_blue" id="jshjdx_zp"></span></td>
                          <td style="padding-top: 50px;" colspan="3" class="align_left borderTop"><span style="padding:0 20px;">价税合计（小写）</span><span class="content_td_blue" id="jshjxx_zp">{{ Amount | NumberFormats }}</span></td>
                        </tr>
                      </tbody></table></td>
                  </tr>
                  <tr>
                    <td rowspan="4" class="align_center"><p>销</p>
                      <p>售</p>
                      <p>方</p></td>
                    <td class="align_left borderNo">名称：</td>
                    <td class="align_left borderNo"><span class="content_td_blue" id="xfmc_zp"></span></td>
                    <td rowspan="4" class="align_center" width="20"><p></p>
                      <p></p></td>
                    <td rowspan="4" class="align_left content_td_blue" width="350" id="bz_zp" valign="top">&nbsp;</td>
                  </tr>
                  <tr>
                    <td class="align_left borderNo">纳税人识别号：</td>
                    <td class="align_left borderNo"><span class="content_td_blue" id="xfsbh_zp"></span></td>
                  </tr>
                  <tr>
                    <td class="align_left borderNo">地址、电话：</td>
                    <td class="align_left borderNo"><span class="content_td_blue" id="xfdzdh_zp"></span></td>
                  </tr>
                  <tr>
                    <td class="align_left borderNo">开户行及账号：</td>
                    <td class="align_left borderNo"><span class="content_td_blue" id="xfyhzh_zp"></span></td>
                  </tr>
                </tbody></table>

            </div>

          </div>

          <!-- <a-descriptions size="small" :column="2" title="" bordered>
          <a-descriptions-item label="购买方" :span="1">
            <div>
              <p><span>名称：</span><span>{{entity.DicKey}}</span></p>
              <p><span>纳税人识别号：</span><span>{{entity.zhanghu}}</span></p>
              <p><span>地址、电话：</span><span>{{ entity.phone }}</span></p>
              <p><span>开户行及帐号：</span><span>{{entity.kaihu}}</span></p>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="密码区" :span="1">
            Prepaid
          </a-descriptions-item>

            <a-descriptions-item  label=""  :span="2" >
              <a-table   :pagination="false" :columns="columnsRead" :data-source="this.newArr" bordered>
                <template slot="name" slot-scope="text">
                  <a>{{ text }}</a>
                </template>
              </a-table>
              </a-descriptions-item>

          <a-descriptions-item label="价税合计（大写）" :span="2">
            <div style="display: flex;justify-content: space-between; align-items: center;">
              <p>❎<span>{{Amount | digitUppercase }}</span></p>
              <p style="margin-right: 20px;">（小写）¥<span>{{Amount}}</span></p>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="销售方">
            <div>
              <p><span>名称：</span><span>北京</span></p>
              <p><span>纳税人识别号：</span><span>北京</span></p>
              <p><span>地址、电话：</span><span>北京</span></p>
              <p><span>开户行及帐号：</span><span>北京</span></p>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="备注">
            {{ entity.beizhu }}
          </a-descriptions-item>
        </a-descriptions> -->
        </template>
        <div style="display: flex; justify-content: space-between;margin-bottom: 100px;">
          <!-- <p style="width: 25%;">收 票 人：<span>{{entity.shoupiaoren}}</span></p>
        <p  style="width: 25%;">手 机 号：<span>{{ entity.Phone }}</span></p>
        <p  style="width: 25%;">地 址：<span>{{entity.shoupiaodizhi}}</span></p> -->
        </div>
      </div>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="handleCancel">上一步</a-button>
        <a-button type="primary" @click="handleOk">提交</a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import SearchCusinfo from './SearchCusinfo'
import moment from 'moment'
import CompanySelect from '@/components/PB/CompanySelect'
const columnsRead = [
  {
    title: '货物或应税劳务、服务名称',
    dataIndex: 'TM_Name',
    scopedSlots: { customRender: 'TM_Name' }
  },
  {
    title: '规格型号',
    dataIndex: 'TM_Specs'
  },
  {
    title: '单位',
    dataIndex: 'TM_Unit'
  },
  {
    title: '数 量',
    dataIndex: 'numskk'
  },
  {
    title: '单 价',
    dataIndex: 'Price'
  },
  {
    title: '金 额',
    dataIndex: 'kmoneys'
  },
  {
    title: '税率',
    dataIndex: 'TaxRate'
  },
  {
    title: '税 额',
    dataIndex: 'TaxPrice'
  }

]
const columns = [
  { title: '出库单号', dataIndex: 'OutboundOrder', width: '20%' },
  { title: '单据日期', dataIndex: 'TIME', width: '20%' },
  { title: '摘要', dataIndex: 'Memo' },
  { title: '联系人', dataIndex: 'Contact', width: '10%' },
  { title: '联系电话', dataIndex: 'ContactPhone', width: '15%' }
].filter(v => !v.hidden) // 增加filter过滤
// 新建
const columns2 = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', width: '230px' },
  { title: '货物编码', dataIndex: 'ventorycode', width: '100px' },
  { title: '货物名称', dataIndex: 'ventoryname', width: '100px' },
  { title: '规格型号', dataIndex: 'specification', width: '100px' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px' },
  { title: '出库数量', dataIndex: 'quantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', width: '100px', align: 'right', hidden: true },
  { title: '已开数量', dataIndex: 'Openedquantity', width: '100px', align: 'right' },
  { title: '开票使用名称', dataIndex: 'TM_Name', width: '150px', align: 'center', scopedSlots: { customRender: 'TM_Name' } },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', width: '150px', align: 'right' },
  { title: '加成率%', dataIndex: 'markup', width: '100px', align: 'right', scopedSlots: { customRender: 'markup' } },
  { title: '开票价格', dataIndex: 'Price', width: '200px', align: 'right', scopedSlots: { customRender: 'Price' } },
  { title: '数量', dataIndex: 'numskk', width: '100px', align: 'right', scopedSlots: { customRender: 'numskk' } },
  { title: '含税金额', dataIndex: 'kmoneys', width: '100px', align: 'right' },
  { title: '税率', dataIndex: 'TaxRate', width: '100px', align: 'right' },
  { title: '税额', dataIndex: 'TaxPrice', width: '100px', align: 'right' },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '60px', fixed: 'right' }
].filter(v => !v.hidden) // 增加filter过滤
// 详情
const columns3 = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    fixed: 'left',
    width: '50px'
  },
  { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'ventorycode', fixed: 'left', width: '100px', align: 'right' },
  { title: '货物名称', dataIndex: 'ventoryname', fixed: 'left', width: '100px', align: 'right' },
  { title: '规格型号', dataIndex: 'specification', width: '100px', align: 'right' },
  { title: '单位', dataIndex: 'compositionQuantity', width: '100px', align: 'right' },
  { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true },
  { title: '开票使用名称', dataIndex: 'TM_Name', scopedSlots: { customRender: 'TM_Name' }, align: 'right', width: '120px' },
  { title: '标准售价', dataIndex: 'origTaxSalePrice', align: 'right', width: '150px' },
  { title: '加成率%', dataIndex: 'markup', align: 'right', scopedSlots: { customRender: 'markup' }, width: '80px' },
  { title: '开票价格', dataIndex: 'Price', align: 'right', scopedSlots: { customRender: 'Price' }, width: '160px' },
  { title: '数量', dataIndex: 'numskk', align: 'right', scopedSlots: { customRender: 'numskk' }, width: '80px' },
  { title: '含税金额', dataIndex: 'kmoneys', align: 'right', width: '160px' },
  { title: '税率', dataIndex: 'TaxRate', align: 'right', width: '60px' },
  { title: '税额', dataIndex: 'TaxPrice', align: 'right', width: '160px' }
].filter(v => !v.hidden) // 增加filter过滤

// 汇总
const SummaryColumns = [
  {
    title: '序号',
    dataIndex: 'Id',
    customRender: (text, row, index) => {
      return index + 1
    },
    width: '50px'
  },
  // { title: '出库单号', dataIndex: 'code', hidden: true },
  { title: '货物编码', dataIndex: 'code', width: '200px' },
  { title: '货物名称', dataIndex: 'name', width: '200px' },
  { title: '规格型号', dataIndex: 'specification', width: '150px' },
  // { title: '单位', dataIndex: 'compositionQuantity', width: '100px' },
  // { title: '出库金额', dataIndex: 'origTaxSaleAmount', align: 'right', hidden: true, },
  // { title: '开票使用名称', dataIndex: 'TM_Name', scopedSlots: { customRender: 'TM_Name' }, align: 'center', width: '120px' },
  // { title: '基本售价', dataIndex: 'InvoicingPrice', align: 'right', width: '150px' },
  // { title: '加成率%', dataIndex: 'markup', align: 'right', scopedSlots: { customRender: 'markup' }, width: '80px' },
  { title: '开票价格', dataIndex: 'InvoicingPrice', align: 'right', scopedSlots: { customRender: 'InvoicingPrice' }, width: '160px' },
  { title: '数量', dataIndex: 'InvoicingQuantity', align: 'right', scopedSlots: { customRender: 'InvoicingQuantity' }, width: '80px' },
  { title: '含税金额', dataIndex: 'InvoicingAmount', align: 'right', width: '160px' },
  // { title: '税率', dataIndex: 'TaxRate', align: 'right', width: '60px' },
  { title: '税额', dataIndex: 'TaxAmount', align: 'right', width: '160px' }
].filter(v => !v.hidden) // 增加filter过滤
export default {
  components: {
    SearchCusinfo,
    CompanySelect
  },
  props: ['back', 'parentObj'],
  data () {
    return {
      columnsRead,
      parentId: '',
      timeDisabled: true,
      options: [
        {
          value: 0,
          label: '张三',
          address: '地址0',
          phone: '0'
        },
        {
          value: 1,
          label: '李四',
          address: '地址1',
          phone: '1'
        },
        {
          value: 2,
          label: '王五',
          address: '地址2',
          phone: '2'
        }
      ],
      details: false,
      Amount: 0,
      data: [],
      start: 0,
      SummaryData: [],
      data2: [],
      allData: [],
      Preview: [],
      selectedRowKeys: [],
      selectedRows: [],
      tableWidth: 0,
      name: '',
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      columns3,
      info: '',
      buyPeopleRead: [],
      visiblity: false,
      setTab: '1',
      SummaryColumns,
      changeVisible: false,
      loadingApply: false,
      changeMarkup: '', // 批量修改加成率
      Summary: false,
      pagination: {
        current: 1,
        pageSize: 20,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      columns0: [],
      pagination2: {
        current: 1,
        pageSize: 20,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['20', '30', '40', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      sorter: { field: 'code', order: 'desc' },
      columns,
      columns2,
      OutboundOrder: '',
      cusid: '',
      time: [],
      buyPeople: [],
      returnActive: false,
      cusname: '',
      queryParam: {
        condition: 'code'
      },
      visible: false,
      visiblees: false,
      loading: false,
      rules: {
        DicKey: [{ required: true, message: '请填写', trigger: 'change' }],
        zhanghu: [{ required: true, message: '请填写18位税号', trigger: 'blur' }]
        // kaihu: [{ required: true, message: '请填写', trigger: 'change' }],
        // phone: [{ required: true, message: '请填写', trigger: 'change' }],
        // Remarks: [{ required: true, message: '请填写', trigger: 'change' }],
        // shoupiaoren: [{ required: true, message: '请填写', trigger: 'change' }],
        // Phone: [{ required: true, message: '请填写', trigger: 'change' }],
        // shoupiaodizhi: [{ required: true, message: '请填写', trigger: 'change' }],
        // beizhu: [{ required: true, message: '请填写', trigger: 'change' }],
      },
      title: '',
      entity: { DicKey: {} },
      flag: true,
      tableHeight: 0,
      precision: 1e10,
      userInfo: {},
      newArr: [],
      selectedRowKeys1: [],
      cancel: false
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys1,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys1 = selectedRowKeys
        },
        getCheckboxProps: record => ({
          props: {
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name
          }
        })
      }
    },

    rowSelection1 () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        //  onChange: this.onSelectChange,
        onSelect: this.onSelect,
        onSelectAll: this.onSelectAll,
        getCheckboxProps: record => ({
          props: {
            disabled: record.Openedquantity >= record.quantity, // Column configuration not to be checked
            name: record.name
          }
        })
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
      this.tableHeight = this.getTableHeight(true) + 24
      console.log(this.time)
      this.getDataList()
    })
  },
  methods: {
    shouCusinfo () {
      // this.back();
      this.OutboundOrder = ''
      // this.$refs.SearchCusinfo.openForm(null, '选择开票客户')
      this.visible = false
      this.visiblees = false
      this.parentObj.$refs.SearchCusinfo.openForm(null, '选择开票客户')
    },
    openForm (id, cCusName, title, userInfo, data, cancel) {
      console.log(this.entity)
      this.entity = { DicKey: {} }
      this.start = 0
      this.tableWidth = 1580
      this.$nextTick(() => {
        this.tableWidth = 1580
      })

      this.details = false
      if (cancel == 'cancel') {
        this.cancel = true
      }
      if (title != '选择出库单') {
        this.Summary = true
      } else {
        this.Summary = false
      }
      this.userInfo = userInfo
      this.cusname = cCusName
      this.$set(this.entity, 'DicKey', this.userInfo.Id)
      this.$set(this.entity, 'zhanghu', this.userInfo.cCusTaxnumber)
      this.$set(this.entity, 'kaihu', this.userInfo.cCusBank + this.userInfo.cCusAccount)
      this.$set(this.entity, 'phone', (this.userInfo.cCusAddress + this.userInfo.cCusPhone))
      this.$set(this.entity, 'cCusEmail', (this.userInfo.cCusEmail))
      this.data2.forEach(item => {
        item.markup = ''
        item.numskk = ''
      })
      this.Amount = 0
      // this.columns2.forEach(item=>{

      // })
      this.$http.post('/CustomerManagement/CustomerInfo/GetDataListByMySelfAndMoreCondition', { 'PageIndex': 1,
        'PageRows': 10000,
        'SortField': 'Id',
        'SortType': 'desc',
        'Search': [{ 'Condition': 'cCusType', 'keyword': '1' }, { Condition: 'cCusName' } ] }).then(res => {
        if (res.Data.length > 0) {
          this.buyPeople = res.Data
          this.buyPeopleRead = res.Data
          // this.entity.DicKey =  res.Data[0].Id  ;
        } else {
          this.name = this.cusname
        }
      }).catch(err => {
        this.$message.error(err)
      })

      this.columns0 = this.columns2
      // let i =this.columns2.findIndex((item)=>item.dataIndex=='compositionQuantity');
      // this.columns2.splice(i,0, { title: '出库数量', dataIndex: 'quantity', width: '20%', align: 'right' },
      //     { title: '已开数量', dataIndex: 'Openedquantity', width: '20%', align: 'right' })
      this.cusid = id
      this.time = [this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)), this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))]
      this.getDataList()
      this.selectedRowKeys = []
      this.selectedRows = []
      this.pagination.current = 1
      this.title = title
      this.visible = true
      if (title == '详情') { // 详情页调。
        this.setTab = '1'
        this.parentId = userInfo.Id
        this.handleDetails(data)
      }
    },

    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
      if (JSON.parse(localStorage.getItem('SELECT_CHECK')) && JSON.parse(localStorage.getItem('SELECT_CHECK')).length > 0) {
        this.selectedRowKeys = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      }
    },
    handleCancel () {
      this.visiblity = false
    },
    changeTime (e) {
      this.timeDisabled = true
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    // 保存
    handleOk () {
      console.log(this.entity, this.Preview, this.data2)
      const Details = []
      this.data2.forEach(item => {
        Details.push({
          'OutboundOrder': item.code,
          'InventoryCode': item.ventorycode,
          'OutboundOrderDetails': item.detailcode,
          'InventoryId': item.idinventory,
          'InventoryName': item.ventoryname,
          'InventoryPrice': item.origTaxSalePrice,
          'Inventoryunit': item.compositionQuantity,
          'Inventoryspec': item.specification,
          'InvoicingQuantity': item.numskk,
          'InvoicingPrice': item.Price,
          'InvoicingAmount': Number(item.kmoneys.replace(/,/g, '')),
          'InvoicingName': item.TM_Name,
          'InvoicingCode': item.Taxproductcode,
          'InvoicingId': item.TaxproductId,
          'Invoicingunit': item.TM_Unit,
          'Invoicingspec': item.TM_Specs,
          'TaxRate': Number(item.TaxRate.replace('%', '')),
          'TaxAmount': Number(item.TaxPrice.replace(/,/g, '')),
          'Markup': item.markup
        })
      })
      const obj = {
        'CusCode': this.userInfo.cCusCode,
        'CusId': this.userInfo.Id,
        'CusName': this.userInfo.cCusName,
        'CusPhone': this.entity.phone,
        'CusAddress': this.entity.phone,
        cCusEmail: this.entity.cCusEmail,
        'TicketbuyerName': this.name,
        'TicketbuyerId': this.entity.DicKey,
        'Accbank': this.entity.kaihu,
        'TaxRegcode': this.entity.zhanghu,
        'PayeeUserId': '1',
        'PayeeUserCode': '1',
        'PayeeUserName': this.entity.shoupiaoren,
        'PayeeUserPhone': this.entity.Phone,
        'PayeeUserAddres': this.entity.shoupiaodizhi,
        'Memo': this.entity.Remarks,
        'Includingtaxinwords': this.Amount,
        'Amountincludingtax': this.Amount,
        // TicketbuyerName:,//购买方姓名.
        // TicketbuyerId:,//购买方id
        Details
      }
      this.$http.post('/InvoiceManagement/Inv_InvoiceApplyMain/SaveInvoicingData', obj).then(res => {
        if (res.Success) {
          this.$message.success('提交成功')
          this.visible = false
          localStorage.removeItem('SELECT_CHECK')
          this.visiblity = false
          this.visiblees = false
          this.$parent.$parent.getDataList()
        } else {
          this.$message.error('提交失败')
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onSelect (record, selected) {
      let select = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      if (selected) {
        this.selectedRowKeys.push(record.OutboundOrder)
      } else {
        // 删除取消选择的
        select = select.filter(item => item != record.OutboundOrder)
        this.selectedRowKeys = this.selectedRowKeys.filter(item => item != record.OutboundOrder)
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('SELECT_CHECK'))) {
        localStorage.setItem('SELECT_CHECK', JSON.stringify(this.selectedRowKeys))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys)
        localStorage.removeItem('SELECT_CHECK')
        localStorage.setItem('SELECT_CHECK', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys.length <= 0
    },
    onSelectAll (selected, selectedRows, changeRows) {
      const select = JSON.parse(localStorage.getItem('SELECT_CHECK'))
      if (selected) {
        changeRows.forEach(item => {
          this.selectedRowKeys.push(item.OutboundOrder)
        })
      } else {
        // //删除取消选择的
        changeRows.forEach(item => {
          select.forEach((item2, index) => {
            if (item2 == item.Id) {
              select.splice(index, 1)
            }
          })
        })
        this.selectedRowKeys = []
      }
      // 如果选择无数据，就创建一个新的加进去。
      if (!JSON.parse(localStorage.getItem('SELECT_CHECK'))) {
        localStorage.setItem('SELECT_CHECK', JSON.stringify(this.selectedRowKeys))
      } else {
        // 反则push
        select.push(...this.selectedRowKeys)
        localStorage.removeItem('SELECT_CHECK')
        localStorage.setItem('SELECT_CHECK', JSON.stringify([...new Set(select)]))
      }
      this.submitDisabled = this.selectedRowKeys.length <= 0
    },
    // 开票信息上一步
    shouorderforgoods () {
      this.OutboundOrder = ''
      this.visiblees = false
      this.time = []
      localStorage.removeItem('SELECT_CHECK')
      this.selectedRowKeys = []
      this.visible = true
    },
    handleChangePrice () { // 批量修改
      console.log(this.selectedRowKeys1)
      this.data2.forEach(item => {
        this.selectedRowKeys1.forEach(ite => {
          if (item.detailcode == ite) {
            item.markup = this.changeMarkup
          }
        })
        this.handleValChange(null, item, null, true)
      })
      this.changeVisible = false
      this.changeMarkup = ''
    },
    handleSearch (value) {
      //  this.buyPeople =  this.buyPeople.filter(data => (data.cCusName = data));

      // this.throttle(()=>{
      const arr = []
      this.buyPeopleRead.forEach(item => {
        if (item.cCusName.indexOf(value) !== -1) {
          arr.push(item)
        }
      })
      this.buyPeople = arr
      // },300)
    },
    handleChange (value) {
      this.buyPeopleRead.forEach(item => {
        if (item.Id === value) {
          this.$set(this.entity, 'zhanghu', item.cCusTaxnumber)
          this.$set(this.entity, 'kaihu', item.cCusBank + item.cCusAccount)
          this.$set(this.entity, 'phone', (item.cCusAddress + item.cCusPhone))
          this.$set(this.entity, 'cCusEmail', (item.cCusEmail))
        }
      })
    },
    // throttle(fn, delay) {
    //   let timer = null;
    //   return function () {
    //     let context = this;
    //     let args = arguments;
    //     if (!timer) {
    //       timer = setTimeout(function () {
    //         fn.apply(context, args);
    //         timer = null;
    //       }, delay);
    //     }
    //   }
    // },
    SummarySubmission () {
      this.$refs.ruleForm.validate(valid => {
        console.log(this.entity)
        if (valid) {
          const reg = /^\d+(\.\d{0,8})?$/
          let flag = false
          let flag1 = false
          let flag2 = false
          this.data2.forEach(item => {
            console.log(item)
            if ((item.quantity - item.Openedquantity) < item.numskk) {
              flag = true
            }
            if (item.numskk === '' || item.TM_Name === '' || item.Price === '') {
              flag1 = true
            }
            if (!reg.test(item.Price)) {
              flag2 = true
            }
          })
          if (this.entity.zhanghu.length != 18) {
            this.$message.warning('请输入18位税号')
            return
          }
          if (flag1) {
            this.$message.warning('信息请填写完毕')
            return
          }
          if (flag2) {
            this.$message.warning('请输入正确的价格，最多八位小数')
            return
          }
          if (!flag) {
            this.visiblity = true
          } else {
            // this.visiblity = true;
            this.$message.warning('数量不能大于出库-已开')
          }
          this.name = this.buyPeople.filter(item => item.Id === this.entity.DicKey)[0].cCusName
          this.newArr = []
          this.Preview = []
          let arr = []
          const obj = {}
          arr = JSON.parse(JSON.stringify(this.data2))
          arr.forEach(item => {
            if (!obj[item.TaxproductId]) {
              obj[item.TaxproductId] = []
              obj[item.TaxproductId].push(item)
            } else {
              obj[item.TaxproductId].push(item)
            }
          })
          for (const i in obj) {
            this.Preview.push(...obj[i])
            let OBJ = {}
            obj[i].forEach((item, index) => {
              console.log(index)
              if (index == 0) {
                OBJ = item
                OBJ.kmoneys = Number(OBJ.kmoneys)
                OBJ.TaxPrice = Number(OBJ.TaxPrice)
              } else {
                console.log(OBJ.numskk, item.numskk)
                OBJ.numskk += item.numskk
                OBJ.kmoneys += Number(item.kmoneys)
                OBJ.TaxPrice += Number(item.TaxPrice)
              }
              console.log(OBJ)
            })
            // if(Number.isInteger(OBJ.kmoneys)){
            //   console.log(123)
            //   OBJ.kmoneys += '.00';
            // }
            // if (Number.isInteger(OBJ.TaxPrice)) {
            //   OBJ.TaxPrice += '.00';
            // }
            this.newArr.push(OBJ)
          }
          this.data2.forEach(item => {
            console.log(item.Price, item.kmoneys)
            if (item.Price % 1 == 0) {
              item.Price = this.$options.filters.NumberFormatss(item.Price)
              // item.Price += '.00';
            }
            if (Number(item.kmoneys.replace(/,/g, '')) % 1 == 0) {
              // item.kmoneys += '.00';
            }
          })
          console.log(this.Preview, obj, this.newArr, this.data2)
        } else {
          return false
        }
      })
    },
    project (select, record) {
      console.log(select, 123, record)
      // return
      // if(select.Taxproductname){
      record.TM_Name = select.Taxproductname
      record.TaxproductId = select.TaxproductId
      record.Taxproductcode = select.Taxproductcode
      record.TM_Unit = select.TM_Unit
      record.TaxRate = select.TM_TaxRate + '%'
      record.TM_Specs = select.TM_Specs
      record.TM_UnitPrice = select.TM_UnitPrice
      // }
      record.origTaxSalePrice = this.$options.filters.NumberFormats(select.TM_UnitPrice)
      // this.handleValChange(null, record,null,true);
      this.$forceUpdate()
    },
    setName (value, record) {
      record.TM_Name = value
      console.log(value, record)
    },
    getDataList () {
      if (!this.cusid) return
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/InvoiceManagement/v_outdata/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: 'Time',
          SortType: 'desc',
          Search: {
            Code: this.cusid,
            OutboundOrder: this.OutboundOrder,
            StartTime: this.time[0] ? this.timeFormat(this.time[0]) : '',
            EndTime: this.time[1] ? this.timeFormat(this.time[1]) : ''
          },
          ...this.filters
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data

          this.allData.push(...new Set(this.data))
          // 清空价格
          this.data.forEach(item => {
            item.TIME = item.TIME.slice(0, 10)
          })
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    // 批量修改价格
    batchChangePrice () {
      this.changeVisible = true
    },
    // 详情
    handleDetails (data, title) {
      this.data2 = []
      if (title) {
        this.info = '退票信息'
        this.returnActive = true
      } else {
        this.info = '开票信息'
        this.returnActive = false
      }

      this.entity = {}
      this.columns0 = this.columns3
      this.cusname = data.CusName
      console.log(data)
      this.name = data.TicketbuyerName
      this.entity.DicKey = data.TicketbuyerName// 购货方
      this.entity.zhanghu = data.TaxRegcode// 税号
      this.entity.kaihu = data.Accbank// 开户行
      this.entity.phone = data.CusAddress
      this.entity.Remarks = data.Memo
      this.entity.shoupiaoren = data.PayeeUserName
      this.entity.Phone = data.PayeeUserPhone
      this.entity.shoupiaodizhi = data.PayeeUserAddres
      this.entity.beizhu = data.Remark
      this.entity.cCusEmail = data.cCusEmail
      this.Amount = data.Amountincludingtax
      data.Details.forEach(item => {
        const obj = {}
        obj.code = item.OutboundOrder
        obj.detailcode = item.OutboundOrderDetails
        obj.id = item.InventoryId
        obj.ventoryname = item.InventoryName
        obj.origTaxSalePrice = this.$options.filters.NumberFormats(item.InventoryPrice)
        obj.compositionQuantity = item.Inventoryunit
        obj.specification = item.Inventoryspec
        obj.numskk = item.InvoicingQuantity
        obj.Price = this.$options.filters.NumberFormatss(item.InvoicingPrice)
        obj.kmoneys = this.$options.filters.NumberFormats(item.InvoicingAmount)
        obj.ventorycode = item.InventoryCode
        obj.TM_Name = item.InvoicingName
        obj.TaxRate = item.TaxRate ? item.TaxRate + '%' : 0 + '%'
        obj.Allkmoneys = Number(item.TaxAmount) + Number(item.InvoicingAmount)
        obj.TaxPrice = this.$options.filters.NumberFormats(item.TaxAmount)
        obj.markup = item.Markup
        this.data2.push(obj)
      })
      console.log(this.entity)
      this.details = true
      this.visible = true
      this.visiblees = true
      this.$set(this, 'tableWidth', 1350)
      this.$nextTick(() => {
        this.$set(this, 'tableWidth', 1350)
      })
    },
    // 详情取消
    closeDetails () {
      this.details = false
      this.visible = false
      this.visiblees = false
      this.data2 = []
      console.log(this.parentObj.$refs)
      // this.$destroy();
      // this.parentObj.Details = false;
      console.log(this.parentObj.$refs)
      this.columns0 = this.columns2
    },
    // 提交下一步
    handleSubmit () {
      this.selectedRows = []
      // console.log(this.allData, this.selectedRowKeys)
      const arr = []
      this.time = []
      this.OutboundOrder = ''
      this.allData.forEach(item => {
        this.selectedRowKeys.forEach(it => {
          if (item.OutboundOrder == it) {
            arr.push(item)
          }
        })
      })
      // 去重
      this.selectedRows = arr.reduce((accumulator, current) => {
        const exists = accumulator.some(item => item.OutboundOrder === current.OutboundOrder)
        if (!exists) {
          accumulator.push(current)
        }
        return accumulator
      }, [])
      if (this.selectedRows.length > 0) {
        this.visible = false
        this.visiblees = true
        // this.entity.DicKey = this.cusname
        this.data2 = this.selectedRows
        this.$set(columns2, 'Price', 0)
        console.log(123)
        this.$nextTick(() => {
          this.loadingApply = true
          console.log(123)
          const arr = []
          this.data2.forEach((item) => {
            arr.push(item.OutboundOrder)
          })
          this.$http
            .post('/InvoiceManagement/ST_RDRecord_b/GetRDRecordList', {
              'PageIndex': 1,
              'PageRows': 10000,
              'SortField': 'Code',
              'SortType': 'desc',
              'Search': {
                'OutboundOrders': arr
              }
            })
            .then((resJson) => {
              const arr = []

              resJson.Data.forEach((item, index) => {
                arr.push(this.$http
                  .post('/InvoiceManagement/Inv_InvoiceApplyMain/GetRDRecordList', {
                    'PageIndex': 1,
                    'PageRows': 20,
                    'SortField': 'TaxproductId',
                    'SortType': 'desc',
                    'Search': {
                      'Keyword': item.ventorycode
                    }
                  })
                  .then((resJson) => {
                    console.log(resJson, item)
                    item.TaxRate = (resJson.Data[0].TM_TaxRate ? resJson.Data[0].TM_TaxRate : 0) + '%'
                    item.TaxPrice = Number(0).toFixed(2)
                    item.kmoneys = Number(0).toFixed(2)
                    this.$set(item, 'TM_Name', resJson.Data[0].Taxproductname)
                    // item.TM_Name = resJson.Data[0].Taxproductname;
                    item.TaxproductId = resJson.Data[0].TaxproductId
                    item.Taxproductcode = resJson.Data[0].Taxproductcode
                    item.TM_Unit = resJson.Data[0].TM_Unit
                    item.TM_Specs = resJson.Data[0].TM_Specs
                    item.origTaxSalePrice = this.$options.filters.NumberFormats(resJson.Data[0].TM_UnitPrice)
                    item.TM_UnitPrice = resJson.Data[0].TM_UnitPrice
                    item.markup = 100
                    item.numskk = item.Unopenedquantity
                    this.handleValChange(null, item, null, true)
                  }).catch(err => {
                    // this.$message.error(err)
                  })
                )
              })
              Promise.all(arr).then(() => {
                this.loadingApply = false
                this.data2 = resJson.Data
                // 清空合计
                this.Amount = 0
                // 计算合计
                this.data2.forEach(ite => {
                  // 精度
                  console.log(ite)
                  // console.log(this.Amount, Number(ite.kmoneys.replace(/,/g, '')), Number(ite.TaxPrice.replace(/,/g, '')))
                  this.Amount = (((this.Amount * this.precision + (Number(ite.kmoneys.replace(/,/g, '')) ? Number(ite.kmoneys.replace(/,/g, '')) : 0) * this.precision) / this.precision)).toFixed(2)
                  // this.Amount = this.Amount  + Number(ite.kmoneys.replace(',', '')) + Number(ite.TaxPrice.replace(',', '')) ;
                })

                this.$forceUpdate()
              })
            })
        })
      } else {
        this.$message.warning('请选择出库单据')
      }
    },
    handleDelete (items) {
      var thisObj = this
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          items.forEach((element) => {
            var index = thisObj.data2.indexOf(element)
            thisObj.data2.splice(index, 1)
            var keyIndex = thisObj.selectedRowKeys.indexOf(element.code)
            thisObj.selectedRowKeys.splice(keyIndex, 1)
          })
          thisObj.$emit('input', [...thisObj.data2])
          resolve()
        })
      })
    },
    // 价格框输入
    handlePriceChange (val, item) {
      const reg = /^\d+(\.\d{0,8})?$/
      console.log(reg.test(val), val.target.value)
      if (reg.test(val.target.value)) {
        // item.Price = Number(val.target.value)
      } else {
        this.$message.warning('请输入正确的价格，最多八位小数')
        return
      }
      item.markup = (Number(val.target.value) / item.TM_UnitPrice * 100) ? (Number(val.target.value) / item.TM_UnitPrice * 100).toFixed(4) : 0
      this.handleValChange(null, item)
    },
    // 精度丢失计算
    actionOperationResult (val1, val2, val3) {
      console.log(val1, val2)
      const p = this.actionOperation(val1, val2, val3)
      return ((val1 * p) * (val2 * p)) * ((val3 * p) || 1) / (p * p * (val3 ? p : 1))
    },
    actionOperation (val1, val2, val3) {
      const len1 = val1.toString().length - val1.toString().indexOf('.') - 1
      const len2 = val2.toString().length - val2.toString().indexOf('.') - 1
      let p = 0
      if (val3) {
        const len3 = val3.toString().length - val3.toString().indexOf('.') - 1
        p = Math.max(len1, len2, len3)
      } else {
        p = Math.max(len1, len2)
      }

      // 避免最终求出结果的长度大于最大长度的时候导致精度丢失 开启下面
      // p += p - Math.min(len1, len2);
      return Math.pow(10, p)
    },
    handleValChange (val, item, index, f) {
      if (item.markup < 0) {
        item.markup = 0
      }
      if (item.numskk < 0) {
        item.numskk = 0
      }
      if (f) {
        item.Price = ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))) ? ((item.markup * item.TM_UnitPrice / 100 * (1 + Number(item.TaxRate.replace('%', '')) / 100))).toFixed(8) : 0
        item.cleanPrice = ((item.markup * item.TM_UnitPrice / 100 * (Number(item.TaxRate.replace('%', '')) / 100))) ? ((item.markup * item.TM_UnitPrice / 100 * (Number(item.TaxRate.replace('%', '')) / 100))).toFixed(8) : 0
      }
      let kmoneys = 0
      let cleanPrice = 0
      // 计算金额
      if (item.Price && Number(item.numskk)) {
        console.log(this.actionOperationResult(item.Price, Number(item.numskk)))
        kmoneys = (this.actionOperationResult(item.Price, Number(item.numskk))).toFixed(2)
        cleanPrice = (this.actionOperationResult(item.Price, Number(item.numskk))).toFixed(2)
      }
      // 计算税额
      if (kmoneys) {
        console.log(this.$options.filters.NumberFormats(kmoneys))
        item.kmoneys = this.$options.filters.NumberFormats(kmoneys)
        console.log(item.markup, item.TM_UnitPrice, item.TaxRate.replace('%', ''), 'sadfojosadigjoisdjagoisadj')
        item.TaxPrice = ((item.markup * item.TM_UnitPrice / 100 * (Number(item.TaxRate.replace('%', '')) / 100))) * item.markup / 100 * Number(item.numskk) ? this.$options.filters.NumberFormats(((item.markup * item.TM_UnitPrice / 100 * (Number(item.TaxRate.replace('%', '')) / 100))) * item.markup / 100 * Number(item.numskk)) : '0.00'
        // item.TaxPrice = this.$options.filters.NumberFormats(Number(cleanPrice)*((item.TaxRate).replace("%", "") / 100));
        console.log(kmoneys, item.TaxPrice)
        // item.Allkmoneys = (Number(kmoneys) + Number(item.TaxPrice.replace(/,/g, ''))).toFixed(2)
      }
      // 清空合计
      this.Amount = 0
      // 计算合计
      this.data2.forEach(ite => {
        // 精度
        // console.log(this.Amount, Number(ite.kmoneys.replace(/,/g, '')), Number(ite.TaxPrice.replace(/,/g, '')))
        this.Amount = (((this.Amount * this.precision + (Number(ite.kmoneys.replace(/,/g, '')) ? Number(ite.kmoneys.replace(/,/g, '')) : 0) * this.precision) / this.precision)).toFixed(2)
        // this.Amount = this.Amount  + Number(ite.kmoneys.replace(',', '')) + Number(ite.TaxPrice.replace(',', '')) ;
      })
      this.$emit('input', [...this.data2])
      this.$forceUpdate()
    },
    callback (e) {
      this.setTab = e
      if (e == '1') {

      } else {
        this.$http.post('/InvoiceManagement/v_applicationsummary/GetDataList', {
          'PageIndex': 1,
          'PageRows': 10000,
          'SortField': 'code',
          'SortType': 'desc',
          'Search': {
            'Condition': 'ParentId',
            'Keyword': this.parentId
          }
        }).then(res => {
          res.Data.forEach(item => {
            // item.InvoicingPrice=this.$options.filters.NumberFormatss(item.InvoicingPrice)
            item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
            item.TaxAmount = this.$options.filters.NumberFormats(item.TaxAmount)
            item.InvoicingQuantity = this.$options.filters.NumberFormat(item.InvoicingQuantity)
          })
          this.SummaryData = res.Data
          // data.Details.forEach(item => {
          //     let obj = {};
          //     obj.code = item.OutboundOrder;
          //     obj.detailcode = item.OutboundOrderDetails;
          //     obj.id = item.InventoryId;
          //     obj.ventoryname = item.InventoryName;
          //     obj.origTaxSalePrice = this.$options.filters.NumberFormats(item.InventoryPrice);
          //     obj.compositionQuantity = item.Inventoryunit;
          //     obj.specification = item.Inventoryspec;
          //     obj.numskk = item.InvoicingQuantity;
          //     obj.Price = this.$options.filters.NumberFormatss(item.InvoicingPrice);
          //     obj.kmoneys = this.$options.filters.NumberFormats(item.InvoicingAmount);
          //     obj.ventorycode = item.InventoryCode;
          //     obj.TM_Name = item.InvoicingName;
          //     obj.TaxRate = item.TaxRate ? item.TaxRate + '%' : 0 + '%';
          //     obj.Allkmoneys = Number(item.TaxAmount) + Number(item.InvoicingAmount);
          //     obj.TaxPrice = this.$options.filters.NumberFormats(item.TaxAmount);
          //     obj.markup = item.Markup;
          //     this.data2.push(obj);
          //   })
        })
      }
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    }
  }
}
</script>
<style scoped>
/deep/ .ant-table-small > .ant-table-content > .ant-table-scroll > .ant-table-header > table > .ant-table-thead > tr > th {
    text-align: center !important;
  }
/deep/ .ant-drawer-header{
  background: rgba(245, 195, 203,0.3);
}
/deep/ .ant-drawer-body{
  background-color: rgba(245, 195, 203,0.3);
}
/deep/ .ant-table-thead > tr > th{
  background: rgba(245, 195, 203,0.3) !important;
}
/deep/ .ant-table-thead >tr {
  background: rgba(245, 195, 203,0.3) !important;
}
/deep/ .ant-table-row-cell-break-word
{
  background-color:rgba(245, 195, 203,0.3);
}
/deep/ .active{
   background-color:rgba(245, 195, 203,0.3) !important;
}
</style>
